package com.niit.hadoop.grep;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class GrepDriver {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        args = new String[]{"^[0-9]*$", "src/main/resources/mapreduce/grep/input", "src/main/resources/mapreduce/grep/output"};

        // 1. 获取Configuration对象
        Configuration conf = new Configuration();
        // args[0]是用户传入的正则表达式
        // 将该正则表达式设置为Configuration对象的属性，属性名为mapregex
        conf.set("mapregex", args[0]);

        // 2. 获取Job对象
        Job job = Job.getInstance(conf);

        // 3. 设置Jar包路径
        job.setJarByClass(GrepDriver.class);

        // 4. 设置Mapper类
        job.setMapperClass(GrepMapper.class);

        // 5. 设置最终输出KV的类型
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(Text.class);

        // 6. 设置Reduce Task的个数为0
        // 即没有Reduce阶段，只有Map阶段
        job.setNumReduceTasks(0);

        // 7. 设置输入和输出路径
        FileInputFormat.addInputPath(job, new Path(args[1]));
        FileOutputFormat.setOutputPath(job, new Path(args[2]));

        // 8. 提交Job
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
